#!/bin/sh
#++++++++++++++++++++ 2 获取当前系统的密码++++++++++++++++++++++++++
read -p "请输入当前系统密码:" SysPassword
if ! type nmap >/dev/null 2>&1;then echo $SysPassword | sudo -S apt install nmap -y;fi
if ! type expect >/dev/null 2>&1;then echo $SysPassword | sudo -S apt install expect -y;fi

# 1.获取网络中开启了22号端口的IP地址和密码的集合
read -p "请输入要扫描的IP段(如192.168.1-250):" IPDuan
echo "正在扫描开启了22好端口的ip"
nmap -p 22 $IPDuan | grep -oP "([0-9]{1,3}\.){3}[0-9]{1,3}" >./ip.txt			#I要扫描的IP段，根据实际情况修改
sed -i "s/$/&:$SysPassword/g" ./ip.txt				# 在扫描出来的IP地址后面加上密码
LocalIP=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}')	#获取本机IP地址,便于后面删除列表中的自己
sed -i /^"${LocalIP}"/d ./ip.txt	#删除列表中的本机IP地址,避免SSh时,操作到本机
cat ./ip.txt
#++++++++++++++++++++ ++++++++++++++++++++++++++
script_dir=$(cd $(dirname $0);pwd)	#取运行目录
UserName=kylin
ClientList=$script_dir/ip.txt   #注意必须要绝对路径

#++++++++++++++++++++ ++++++++++++++++++++++++++
if [ ! -d ~/.ssh ];then mkdir ~/.ssh && ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa -q; fi	 # 创建操作机上的公钥,id开头的2个文件，其中id_rsa.pub就是公钥文件
# 1. 批量ssh认证建立
for p in $(cat $ClientList)		#注意ip.txt文件的绝对路径
do
    ip=$(echo "$p"|cut -f1 -d":")	#取ip.txt文件中的ip地址
    password=$(echo "$p"|cut -f2 -d":")	#取ip.txt文件中的密码
	#echo ssh-copy-id -i ~/.ssh/id_rsa.pub $UserName@$ip 

    # 1.1 expect自动交互开始
	expect -c "
    set timeout 5;
	spawn ssh-copy-id -i /home/kylin/.ssh/id_rsa.pub $UserName@$ip 
		expect {
			\"*yes/no*\" {send \"yes\r\"; exp_continue}
			\"*password*\" {send \"$password\r\"; exp_continue}
			\"*密码：*\" {send \"$password\r\";exp_continue}
			}
"
done

clear
echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
echo $ip"/"$password"/"$script_dir
# 2. 通过ssh批量执行命令
#cmd1="echo $SysPassword | sudo -S mount -t cifs -o username=administrator,password=123qwe //192.168.1.186/temp /mnt/lv"
#cmd2="echo $SysPassword | sudo -S rm -rf /opt/InfreeClient/audioClient"
#cmd3="echo $SysPassword | sudo -S cp /mnt/lv/audioClient /opt/InfreeClient/"


for h in $(cat $ClientList|cut -f1 -d":")
do

	expect -c "
    set timeout 5;
	spawn scp -r /home/kylin/桌面/config.ini $UserName@$h:/opt/InfreeClient
	spawn scp -r /home/kylin/桌面/SSH-设置WOL.sh $UserName@$h:/home/kylin/桌面
	spawn ssh $UserName@$h /home/kylin/桌面/SSH-设置WOL.sh
		expect {
			\"*yes/no*\" {send \"yes\r\"; exp_continue}
			\"*password*\" {send \"$password\r\"; exp_continue}
			}
"
#echo $h
done



